<template>
    <div class="editInfo">
      <nav-bar :title="titleObj[type]" :path="path" :right="right" @rightClick="save"></nav-bar>
      <div class="content">
        <van-field v-if="type !== 'avatar'" class="field" v-model="inputValue"></van-field>
        <van-uploader
          v-else
          v-model="fileList"
          :max-count="1"
          :before-read="beforeRead"
          :after-read="afterRead"
          @delete="deleteEvent"/>
      </div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { auEdit, upload } from '@/api/my'

export default {
  name: 'editInfo',
  computed: {
    ...mapState(['userInfo'])
  },
  data () {
    return {
      path: 'myInfo',
      inputValue: '',
      type: this.$route.query.type,
      right: '',
      titleObj: {
        nickname: '修改昵称',
        intro: '修改个人简介',
        position: '修改岗位',
        avatar: '修改头像'
      },
      fileList: []
    }
  },
  watch: {
    inputValue (newValue) {
      if (newValue !== this.userInfo[this.type] && newValue !== '') {
        this.right = '保存'
      } else {
        this.right = ''
      }
    }
  },
  created () {
    if (this.userInfo.avatar) {
      this.fileList[0] = { url: process.env.VUE_APP_URL + this.userInfo.avatar }
    }
    if (this.type === 'position') {
      this.path = 'my'
    }
    this.inputValue = this.userInfo[this.type]
  },
  methods: {
    save () {
      if (this.right === '') {
        return
      }
      this.editInfo({ [this.type]: this.inputValue })
    },
    editInfo (obj) {
      this.$toast.loading({
        duration: 0
      })
      auEdit(obj).then(() => {
        this.$toast.success('修改资料成功')
        this.$router.push(this.path)
        // 调用仓库异步方法刷新数据
        this.$store.dispatch('refreshUserInfo')
      }).catch(() => {})
    },
    beforeRead (file) {
      const isImg = file.type === 'image/png'
      const limit2M = file.size / 1024 / 1024 < 2
      if (!isImg) {
        this.$toast.fail('请上传PNG格式的图片')
      }
      if (!limit2M) {
        this.$toast.fail('请上传2M以内的图片')
      }
      return isImg && limit2M
    },
    async afterRead (file) {
      const _formData = new FormData()
      _formData.append('files', file.file)
      this.$toast.loading({
        duration: 0
      })
      const res = await upload(_formData)
      console.log(res)
      this.$toast.success('上传成功!')
      this.inputValue = res.data.data[0].id
    },
    deleteEvent () {
      this.inputValue = ''
    }
  }
}
</script>

<style lang="less" scoped>
  .editInfo {
    .content {
      padding: 19px @p15 0;
      .field {
        background-color: #f7f4f5;
        border-radius: 4px;
      }
    }
  }
</style>
